import {GameState} from "../enum"
import {Generate} from "../../wailsjs/go/main/App"

let timerInterval = null

export const GameEntity = {
    // 游戏状态：pending=准备中, loading=加载中, started=游戏中，paused=暂停，successful=挑战成功，failure=挑战失败
    state: GameState.PENDING,
    // 计时器
    timer: 0,
    // 已提示次数
    prompted: 0,
    // 已错误次数
    mistaken: 0,

    board: {},

    // 游戏难度
    difficulty: 2,
    // 最大提示次数
    maxPrompts: 3,
    // 最多错误次数
    maxMistakes: 3,

    // 初始化
    init() {
        this.stopTime()
        this.state = GameState.PENDING
        this.timer = this.prompted = this.mistaken = 0
        this.board.init()
    },

    // 新游戏
    async new(options = {}) {
        this.init()
        this.loading()

        this.maxPrompts = options.maxPrompts || this.maxPrompts
        this.maxMistakes = options.maxMistakes || this.maxMistakes

        let res = await Generate({difficulty: options.difficulty})
        this.board.solution = res.solution
        this.board.subject = res.subject

        this.start()
    },

    // 游戏调试
    async test() {
        await this.new({difficulty: -1})
    },

    // 重玩
    replay() {
        let {solution, subject} = this.board

        this.init()
        this.board.solution = solution
        this.board.subject = subject
    },

    // 开始计时
    startTime() {
        if (!this.getIsTiming()) {
            timerInterval = setInterval(() => {
                this.timer++
            }, 1000)
        }
    },
    // 停止计时
    stopTime() {
        if (this.getIsTiming()) {
            clearInterval(timerInterval)
            timerInterval = null
        }
    },
    // 是否计时
    getIsTiming() {
        return timerInterval !== null
    },


    loading() {
        this.state = GameState.LOADING
        this.stopTime()
    },

    // 开始游戏
    start() {
        this.state = GameState.STARTED
        this.startTime()
    },

    // 暂停游戏
    pause() {
        if (this.state === GameState.STARTED) {
            this.state = GameState.PAUSED
            this.stopTime()
        }
    },

    // 挑战失败
    failure() {
        this.state = GameState.FAILURE
        this.stopTime()
    },

    // 挑战成功
    successful() {
        this.state = GameState.SUCCESSFUL
        this.stopTime()
    },
}
